package Concurrency.basic.cooperation;

/**
 * 协作例子：异步结果
 * MyExecutor.execute：异步执行任务
 */

import java.util.concurrent.Callable;

public class MyExecutor {
    public <V> MyFuture<V> execute(final Callable<V> task) throws InterruptedException {
        final Object lock = new Object();
        final ExecuteThread<V> thread = new ExecuteThread<>(task, lock);
        thread.start();
        Thread.sleep(1000);
        MyFuture<V> future = new MyFuture<V>() {
            @Override
            public V get() throws Exception {
                System.out.println("MyFuture attempt to acquire lock");
                synchronized (lock) {
                    while (!thread.isDone()) {
                        try {
                            System.out.println("MyFuture waiting for lock");
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (thread.getException() != null) {
                        throw thread.getException();
                    }
                    return thread.getResult();
                }
            }
        };
        return future;
    }

    public static void main(String[] args) throws InterruptedException {
        MyExecutor executor = new MyExecutor();
        //子任务
        Callable<Integer> subTask = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                //...执行异步任务
               int millis = (int)(Math.random() * 1000);
               Thread.sleep(millis);
               return millis;
            }
        };
        //异步调用
        MyFuture<Integer> future = executor.execute(subTask);
        //...执行其他操作
        try {
            //获取异步调用的结果
            Integer result = future.get();
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
